package util

import (
	"encoding/json"
	"reflect"
	"unsafe"
)

// ParseStringToBytes converts string to byte slice without a memory allocation.
func ParseStringToBytes(s string) (b []byte) {
	sh := *(*reflect.StringHeader)(unsafe.Pointer(&s))
	bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
	bh.Data, bh.Len, bh.Cap = sh.Data, sh.Len, sh.Len
	return b
}

// 将RawMessage强行按字符串解读
func ParseRawMessageToString(value json.RawMessage) (str string) {
	// 符合字符串格式，解码出即可
	if err := json.Unmarshal(value, &str); err == nil {
		return
	}
	// 不符合字符串格式，强转为字符串
	return *(*string)(unsafe.Pointer(&value))
}
